﻿#include "JoinVectorFunction.h"
#include <QDebug>
//#include <QTableView>

#include "BaseVector.h"
#include "TableInSceneWidget.h"
#include "TableInSceneModel.h"

class JoinVectorFunction::JoinVectorFunctionPrivate :QObject
{
public:
	int in_params[16];
	int out_params[1];
	int in_count;
	int out_count;
public:
	JoinVectorFunctionPrivate(QObject*parent) :QObject(parent)
	{
		in_count = 4;
		out_count = 1;

		in_params[0] = FPT_PTR;
		in_params[1] = FPT_STRING;
		in_params[2] = FPT_NUMBER;
		in_params[3] = FPT_NONE; // 至少四个参数
		out_params[0] = FPT_VECTOR;
	}

};

JoinVectorFunction::JoinVectorFunction(QObject *parent)
	: QObject(parent),private_ptr(new JoinVectorFunctionPrivate(this))
{
}

JoinVectorFunction::~JoinVectorFunction()
{
}

static int JoinVectorFunction_FUNCTION(struct variant_s *in, int in_count, struct variant_s *out, void*tag)
{
	if (4 > in_count)
		return ERR_PARAM_NOT_MATCH;

	// 判断第一个参数
	if (VALUETYPE_VOID_PTR != in[0].type)
		return ERR_DATATYPE_NOT_MATCH;
	if (nullptr == in[0].u.ptr)
		return ERR_DATATYPE_NOT_MATCH;

	// 判断第二个参数
	if (VALUETYPE_STRING != in[1].type)
		return ERR_DATATYPE_NOT_MATCH;
	if (nullptr == in[1].u.ptr)
		return ERR_DATATYPE_NOT_MATCH;
	QString sep = ((struct astring_s*)in[1].u.ptr)->value;

	QVector<int> cols;
	for (int i = 2; i < in_count; i++) {
		switch (in[i].type) {
		case VALUETYPE_DOUBLE:
			cols.append((int)in[i].u.d);
			break;
		case VALUETYPE_INTEGER:
			cols.append(in[i].u.i);
			break;
		default:
			return ERR_DATATYPE_NOT_MATCH;
		}
	}


	AstScene*as = nullptr;
	TableInSceneWidget*ptr = nullptr;
	try {
		as = (AstScene*)in[0].u.ptr;
		ptr = dynamic_cast<TableInSceneWidget*>(as->widget());
	}
	catch (...) {}

	if (!ptr)
		return -1;

	//TableInSceneModel*m = ptr->model();

	BaseVector*pv = new BaseVector(nullptr);
	out->type = VALUETYPE_ARRAY;
	out->u.ptr = (IVector*)pv;
	out->fn_addref = BaseVector::addref_fn;
	out->fn_release = BaseVector::release_fn;

	qDebug() << "join vector:" << out->u.ptr << ", fn:" << BaseVector::addref_fn << "," << BaseVector::release_fn;

	QVector<QVariant>*pd = pv->data();
	TableInSceneModel*m = ptr->model();

	QString str;
	QVariant val;
	QModelIndex idx;
	for (int i = 0; i < m->rowCount(); i++) {
		str.clear();
		for (auto n : cols) {
			if (!str.isEmpty())
				str += sep;
			idx = m->index(i, n);
			if (idx.isValid()) {
				val = m->data(idx, Qt::EditRole);
				str += val.toString();
			}
		}
		pd->append(str);
	}
	
	return ERR_OK;
}

AstFunction* JoinVectorFunction::operator()()
{
	return dynamic_cast<AstFunction*>(this);
}

QString JoinVectorFunction::name()
{
	return "JoinVector";
}
int* JoinVectorFunction::outputTypes()
{
	return private_ptr->out_params;
}
int JoinVectorFunction::outputCount()
{
	return private_ptr->out_count;
}
int* JoinVectorFunction::inputTypes()
{
	return private_ptr->in_params;
}
int JoinVectorFunction::inputCount()
{
	return private_ptr->in_count;
}
void* JoinVectorFunction::function()
{
	return JoinVectorFunction_FUNCTION;
}
